package com.iflysse.controller;

import com.iflysse.common.ResultEnum;
import com.iflysse.pojo.bo.req.UserBoReq;
import com.iflysse.pojo.bo.resp.UserBoResp;
import com.iflysse.pojo.vo.common.CommonVoResp;
import com.iflysse.pojo.vo.req.*;
import com.iflysse.pojo.vo.resp.*;
import com.iflysse.services.UserService;
import com.iflysse.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

@RestController
@RequestMapping("/user")
@Api(value = "公用用户模块接口")
public class UserController {
    @Autowired
    UserService userService;


    /**
     * 校验链接是否有效
     */
    @PostMapping("/checkEmailLinkIsOk")
    @ApiOperation(value = "校验链接是否有效")
    public CheckEmailLinkIsOkVoResp doCheckEmailLinkIsOk(CheckEmailLinkIsOkVoReq checkEmailLinkIsOkVoReq) {

        CheckEmailLinkIsOkVoResp checkEmailLinkIsOkVoResp = new CheckEmailLinkIsOkVoResp();
        return checkEmailLinkIsOkVoResp;
    }


    /**
     * 修改头像
     *
     * @throws IOException
     */
    @PostMapping("/updateUserHeadImage")
    @ApiOperation(value = "修改头像接口")
    public CommonVoResp doUpdateUserHeadImage(UserHeadImageVoReq userHeadImageVoReq) {
        CommonVoResp commonVoResp = new CommonVoResp();
        return commonVoResp;
    }

    @PostMapping("/updateUserInfo")
    @ApiOperation(value = "修改用户信息接口")
    public CommonVoResp doUpdateUserInfo(UpdateUserInfoVoReq updateUserInfoVoReq) {
        CommonVoResp commonVoResp = new CommonVoResp();
        return commonVoResp;
    }


    /**
     * 查询用户个人信息接口
     *
     * @param queryUserInfoVoReq
     * @return
     */
    @PostMapping("/queryUserInfo")
    @ApiOperation(value = "查询用户信息，老师端学生端共有")
    public QueryUserInfoVoResp queryUserInfo(QueryUserInfoVoReq queryUserInfoVoReq) {

        QueryUserInfoVoResp queryUserInfoVoResp = new QueryUserInfoVoResp();

        return queryUserInfoVoResp;

    }


    /**
     * 重置密码操作
     *
     * @param resetPasswordVoReq
     * @return
     */
    @PostMapping("/resetPassword")
    @ApiOperation(value = "用户重置密码接口")
    public CommonVoResp resetPassword(ResetPasswordVoReq resetPasswordVoReq) {
        /**
         * TODO  1：校验新密码和确认新密码是否正确    2：校验验证码是否正确   3：完成重置密码
         */
        CommonVoResp commonVoResp = new CommonVoResp();
        commonVoResp.setCode(1000);
        commonVoResp.setMsg("重置密码成功");
        return commonVoResp;
    }


    /**
     * 找回密码操作
     *
     * @param retrievePasswordVoReq
     * @return
     */
    @PostMapping("/retrievePassword")
    @ApiOperation(value = "用户找回密码接口")
    public CommonVoResp retrievePassword(RetrievePasswordVoReq retrievePasswordVoReq) {
        /**
         * TODO  1：校验姓名和邮箱是否一致    2：校验验证码是否正确   3：链接后追加参数：用户的唯一标识   4：邮件发送
         */
        CommonVoResp commonVoResp = new CommonVoResp();
        commonVoResp.setCode(1000);
        commonVoResp.setMsg("链接发送成功");
        return commonVoResp;
    }


    @PostMapping("/login")
    @ApiOperation(value = "用户登录接口")
    public UserVoResp login(UserVoReq userVoReq,HttpServletRequest request) throws Exception {

        UserVoResp userVoResp = new UserVoResp();
        /**
         * TODO 调用登录的业务接口，获取返回信息
         */

        // 前端传参的非空检查
        if(userVoReq != null){
            if(StringUtils.isEmpty(userVoReq.getCode())
                    || StringUtils.isEmpty(userVoReq.getCodeId())
                    || StringUtils.isEmpty(userVoReq.getPassWord())
                    || StringUtils.isEmpty(userVoReq.getUserName())) {
                userVoResp.setCode(ResultEnum.NOPARAMETER.getCode());
                userVoResp.setMsg(ResultEnum.NOPARAMETER.getMsg());
                return userVoResp;
            }
        }

        // 验证码的检查

        String fromSessionCode = (String)request.getSession().getAttribute(userVoReq.getCodeId());

        // 真实环境使用，测试不使用
        /*if(!userVoReq.getCode().equals(fromSessionCode)){
            userVoResp.setCode(ResultEnum.CODEERROR.getCode());
            userVoResp.setMsg(ResultEnum.CODEERROR.getMsg());
            return userVoResp;
        }*/

        // 账户和密码的校验

        UserBoReq userBoReq = new UserBoReq();
        userBoReq.setUserName(userVoReq.getUserName());
        userBoReq.setPassWord(userVoReq.getPassWord());

        UserBoResp reulst = userService.login(userBoReq);

        // token信息
        String token = JwtUtil.createToken( reulst.getUserId(), reulst.getRole()) ;


        /*UserResp userResp = new UserResp();
        userResp.setRole("1");
        userResp.setUserId("123123");
        userResp.setToken("qweqweqwe");*/
        userVoResp.setCode(3000);
        userVoResp.setMsg("登录成功");
        UserResp userResp = new UserResp();
        userResp.setRole(reulst.getRole());
        userResp.setToken(token);
        userResp.setUserId(reulst.getUserId());
        userVoResp.setResult(userResp);
        return userVoResp;
    }


    /**
     * 图片验证码
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @PostMapping("/code")
    @ApiOperation(value = "图形验证码")
    public CodeVoResp createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("验证码请求");
        //设置打印到浏览器的数据格式
        response.setContentType("image/gif");

        // 清除页面缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        //创建一张缓存图片
        BufferedImage image = new BufferedImage(100, 30, BufferedImage.TYPE_INT_RGB);

        //根据图片对象获取出图片的绘制对象
        Graphics g = image.getGraphics();
        //根据绘制对象来给图片增加背景颜色
        g.setColor(Color.red);
        //根据绘制对象来确定背景颜色的范围
        g.fillRect(0, 0, 100, 30);

        //随机生成一个数
        Random r = new Random();

        //往图片中绘制验证码  4
        g.setColor(Color.BLACK);

        StringBuffer sbCode = new StringBuffer();
        int x = 20;
        for (int i = 0; i < 4; i++) {
            int txt = r.nextInt(10);
            String str = String.valueOf(txt);
            g.drawString(str, x, 20);//
            sbCode.append(str);
            x = x + 20;
        }

        //TODO 生成验证码的唯一标识
        String codeId = "code";

        //TODO 设置session的有效期
        //将验证码存到session中，方便登录时来获取这个验证去校验用户登陆时所输入的验证码是否正确
        request.getSession().setAttribute(codeId, sbCode.toString());

        BASE64Encoder encoder = new BASE64Encoder();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        ImageIO.write(image, "gif", baos);//写入流中
        byte[] bytes = baos.toByteArray();//转换成字节
        String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
        //删除 \r\n
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");

        System.out.println(png_base64);


        CodeVoResp codeVoResp = new CodeVoResp();
        CodeResp codeResp = new CodeResp();
        codeResp.setCodeId(codeId);
        codeResp.setBaseImage(png_base64);
        codeVoResp.setResult(codeResp);
        codeVoResp.setCode(1000);
        codeVoResp.setMsg("验证码生成成功");
        return codeVoResp;


    }
}
